package com.zhudi.develop_demo_as;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.update.UmengUpdateAgent;
import com.zhudi.develop.util.ZhudiDebugLog;
import com.zhudi.develop.util.ZhudiToastSingle;
import com.zhudi.develop_demo_as.entity.ModelTest;
import com.zhudi.develop_demo_as.entity.parser.ModelTestParser;
import com.zhudi.develop_demo_as.network.NetworkService;
import com.zhudi.develop_demo_as.ui.fragment.HomeFragment;
import com.zhudi.develop_demo_as.ui.fragment.MineFragment;
import com.zhudi.develop_demo_as.ui.fragment.MoreFragment;
import com.zhudi.develop_demo_as.ui.fragment.StoreFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;


public class MainActivity extends BaseActivity{
    private Context context;
    //NetReceiver mReceiver = new NetReceiver();
    //IntentFilter mFilter = new IntentFilter();
    /** 设置退出的两次间隔时间 **/
    private long exitTime;
//    /** 用于对Fragment进行管理*/
//    //private FragmentManager fragmentManager;
//    /**用于展示消息的Fragment*/
//    private HomeFragment homeFragment;
//    /**用于展示联系人的Fragment*/
//    private StoreFragment storeFragment;
//    /** 用于展示动态的Fragment*/
//    private MineFragment mineFragment;
//    /**用于展示设置的Fragment*/
    private MoreFragment moreFragment;
    @Bind({ R.id.tvHome, R.id.tvNear, R.id.tvAction, R.id.tvMine })
    List<TextView> tabTv;
    public List<BaseFragment> fragments;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ZhudiDebugLog.d("onCreate---->");
        context = this;
        if (null != savedInstanceState){
            boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
            double myDouble = savedInstanceState.getDouble("myDouble");
            ZhudiToastSingle.showToast(context, String.valueOf(myDouble), Toast.LENGTH_SHORT, -1);
        }
        initView();
        //setListener();
        //registerNetReceiver();
        UmengUpdateAgent.update(this);
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        getDataTest();
    }

    private void getDataTest(){
        String url = "http://www.kuaidi100.com/query?type=yuantong&postid=200259801921";
        NetworkService<ArrayList<ModelTest>> service = new NetworkService<ArrayList<ModelTest>>("", new NetworkService.NetworkListener<ArrayList<ModelTest>>() {
            @Override
            public void onReceiveResult(ArrayList<ModelTest> result) {
                List<ModelTest> test = result;
                ZhudiDebugLog.d(test.toString());
            }

            @Override
            public void onFailure(int code, String msg) {
                ZhudiDebugLog.d("onFailure---->" + msg);
            }
        });
        service.configContext(this);
        service.configAnalyze(new ModelTestParser());
        service.getSubmit(url);
    }

    /**防止activity数据丢失 */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        ZhudiDebugLog.d("onRestoreInstanceState---->");
//        boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
//        double myDouble = savedInstanceState.getDouble("myDouble");
//        ZhudiToastSingle.showToast(context, String.valueOf(myDouble), Toast.LENGTH_SHORT, -1);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        ZhudiDebugLog.d("onSaveInstanceState---->");
        savedInstanceState.putBoolean("MyBoolean", true);
        savedInstanceState.putDouble("myDouble", 1.9);
        super.onSaveInstanceState(savedInstanceState);

    }
    /**防止activity数据丢失结束 */

    private void initView() {
        fragments = new ArrayList<BaseFragment>();
        fragments.add(new HomeFragment());
        fragments.add(new StoreFragment());
        fragments.add(new MineFragment());
        fragments.add(new MoreFragment());

        new FragmentTabAdapter(this, fragments, R.id.content, tabTv);
    }


    class FragmentTabAdapter implements OnClickListener {
        FragmentActivity fragmentActivity;
        List<BaseFragment> fragments;
        int fragmentContentId;
        private int currentTab;
        private List<TextView> list;

        public FragmentTabAdapter(FragmentActivity fragmentActivity, List<BaseFragment> fragments, int fragmentContentId, List<TextView> List) {
            this.fragmentActivity = fragmentActivity;
            this.fragments = fragments;
            this.fragmentContentId = fragmentContentId;

            //加载第一个界面
            FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
            ft.add(fragmentContentId, fragments.get(0));
            ft.commit();
            list = new ArrayList<TextView>();
            for (int i = 0; i < List.size(); i++) {
                list.add(List.get(i));
                List.get(i).setOnClickListener(this);
            }
            list.get(0).setSelected(true);
        }


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == v.getId()) {
                    list.get(i).setSelected(true);
                    Fragment fragment = fragments.get(i);
//                    FragmentTransaction ft = obtainFragmentTransaction(i);
                    FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
                    getCurrentFragment().onPause(); // 暂停当前tab
                    getCurrentFragment().onStop(); // 暂停当前tab
                    if (fragment.isAdded()) {
                        fragment.onStart(); // 启动目标tab的onStart()
                        fragment.onResume(); // 启动目标tab的onResume()
                    } else {
                        ft.add(fragmentContentId, fragment);
                    }
                    showTab(i); // 显示目标tab
                    ft.commit();
                } else
                    list.get(i).setSelected(false);
            }
        }


        private void showTab(int idx) {
            for (int i = 0; i < fragments.size(); i++) {
                Fragment fragment = fragments.get(i);
                FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
                if (idx == i) {
                    ft.show(fragment);
                } else {
                    ft.hide(fragment);
                }
                ft.commit();
            }
            currentTab = idx; // 更新目标tab为当前tab
        }

        /**
         * 获取一个带动画的FragmentTransaction
         * @param index
         * @return
         */
//        private FragmentTransaction obtainFragmentTransaction(int index){
//            FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
//            // 设置切换动画
//            if(index > currentTab){
//                ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
//            }else{
//                ft.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_right_out);
//            }
//            return ft;
//        }

        public int getCurrentTab() {
            return currentTab;
        }

        public Fragment getCurrentFragment(){
            return fragments.get(currentTab);
        }
    }
//
//    private void setListener() {
//        for (int i = 0; i < tabTv.size(); i++) {
//            tabTv.get(i).setOnClickListener(this);
//        }
//    }
//
//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.tvHome://首页
//                setTabSelection(0);
//                break;
//            case R.id.tvNear://附近
//                setTabSelection(1);
//                break;
//            case R.id.tvAction://我的
//                setTabSelection(2);
//                break;
//            case R.id.tvMine://我的
//                setTabSelection(3);
//                break;
//        }
//    }
//
//    /**
//     * 根据传入的index参数来设置选中的tab页。
//     *
//     * @param index
//     *            每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
//     */
//    private void setTabSelection(int index) {
//        //每次选中之前先清楚掉上次的选中状态  然后设置当前的状态
//        resetAndSetTabs(index);
//        //开启一个Fragment事务
//        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        //先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
//        hideFragments(transaction);
//        switch (index) {
//            case 0:
//                if (homeFragment == null) {
//                    // 如果MessageFragment为空，则创建一个并添加到界面上
//                    homeFragment = new HomeFragment();
//                    transaction.add(R.id.content, homeFragment);
//                } else {
//                    // 如果MessageFragment不为空，则直接将它显示出来
//                    transaction.show(homeFragment);
//                }
//                break;
//            case 1:
//                if (storeFragment == null) {
//                    // 如果ContactsFragment为空，则创建一个并添加到界面上
//                    storeFragment = new StoreFragment();
//                    transaction.add(R.id.content, storeFragment);
//                } else {
//                    // 如果ContactsFragment不为空，则直接将它显示出来
//                    transaction.show(storeFragment);
//                }
//                break;
//            case 2:
//                if (mineFragment == null) {
//                    // 如果NewsFragment为空，则创建一个并添加到界面上
//                    mineFragment = new MineFragment();
//                    transaction.add(R.id.content, mineFragment);
//                } else {
//                    // 如果NewsFragment不为空，则直接将它显示出来
//                    transaction.show(mineFragment);
//                }
//                break;
//            case 3:
//                if (moreFragment == null) {
//                    // 如果SettingFragment为空，则创建一个并添加到界面上
//                    moreFragment = new MoreFragment();
//                    transaction.add(R.id.content, moreFragment);
//                } else {
//                    // 如果SettingFragment不为空，则直接将它显示出来
//                    transaction.show(moreFragment);
//                }
//                break;
//        }
//        transaction.commit();
//    }
//
//    /**
//     * 重置的Tab后设置Tab
//     */
//    private void resetAndSetTabs(int index) {
//        for (int i = 0; i < tabTv.size(); i++) {
//           tabTv.get(i).setSelected(false);
//        }
//        tabTv.get(index).setSelected(true);
//    }
//
//    /**
//     * 将所有的Fragment都置为隐藏状态。
//     *
//     * @param transaction 用于对Fragment执行操作的事务
//     */
//    private void hideFragments(FragmentTransaction transaction) {
//        if (homeFragment != null) {
//            transaction.hide(homeFragment);
//        }
//        if (storeFragment != null) {
//            transaction.hide(storeFragment);
//        }
//        if (mineFragment != null) {
//            transaction.hide(mineFragment);
//        }
//        if (moreFragment != null) {
//            transaction.hide(moreFragment);
//        }
////        if (homeFragment != null || storeFragment != null || mineFragment != null || moreFragment != null) {
////            transaction.commit();
////        }
//    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                this.exitApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 退出程序
     */
    private void exitApp() {
        // 判断2次点击事件时间
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ZhudiToastSingle.showToast(MainApplication.getInstance(), getString(R.string.exit_software), Toast.LENGTH_SHORT, -1);
            exitTime = System.currentTimeMillis();
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }


//    private void registerNetReceiver() {
//        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        registerReceiver(mReceiver, mFilter);
//    }
//
//	@Override
//	protected void onDestroy() {
//		super.onDestroy();
//		unregisterReceiver(mReceiver);
//	}



}
